<template>
    <div class="flex flex-row" style="width: 100%;">
        <div id="container" class="map"></div>

        <div class="flex-1">
            <el-table :data="engineerList">
                <!-- <el-table-column type="selection" /> -->
                <el-table-column label="姓名" align="center" width="100">
                    <template #default="{ row }">{{ row.wxUserDto.realName }}</template>
                </el-table-column>
                <el-table-column property="phone" label="手机" align="center" width="150">
                    <template #default="{ row }">{{ row.wxUserDto.phone }}</template>
                </el-table-column>
                <el-table-column property="address" label="地址" align="center">
                    <template #default="{ row }">{{ row.locationDto.formattedAddress }}</template>
                </el-table-column>
                <el-table-column label="操作" width="80" align="center">
                    <template #default="{ row }">
                        <div>
                            <el-popconfirm title="是否要派单？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="submitAssign(row)">
                            <template #reference>
                                <!-- 未指派的状态删除按钮可用，其他场景不可用 -->
                                <el-button type="primary" size="small" text >{{ state.assignedUserId == row.wxUserDto.id ? '已分配' : '派单' }}</el-button>
                            </template>
                        </el-popconfirm>

                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue"
import AMapLoader from "@amap/amap-jsapi-loader";
import { api_orders_dispatch } from "~/api/ordersApi";
import { api_location_nearestEngineer } from "~/api/locationApi";
import { toast, toastWarn } from '~/composables/util'


AMapLoader.reset()
//props
const props = defineProps({
    assignProps: Object,
})


const engineerList = ref([])

const state = reactive({
    map: null,
    placeSearch: null,
    autoComplete: null,
    marker: null,
    form: {
        address: '',
        lng: '',
        lat: '',
    },
    areaList: [],
    address: '',
    assignedUserId: null,


})

watch(
    () => props.assignProps,
    (newProps) => {
        console.log('assgin order info: ', newProps)
        state.assignedUserId = newProps.engineerDto?.id
        getTargetLocationArroundEngineer(newProps)
    }
)

// 获取目标地址附近的工程师列表
const getTargetLocationArroundEngineer = (newProps) => {
    let longitude = newProps.orderLocationDto.longitude
    let latitude = newProps.orderLocationDto.latitude
    api_location_nearestEngineer(longitude, latitude, 20).then(res => {
        engineerList.value = res
    })
}



// 生命周期函数
onMounted(() => {

    // 2
    window._AMapSecurityConfig = {
        securityJsCode: '8ffe92977bb0f5d65f8cf83a59a5186b', // https://console.amap.com/dev/key/app   绑定的服务为 Web端
    }

    console.log('props 经纬度：', [props.assignProps.orderLocationDto.longitude, props.assignProps.orderLocationDto.latitude])
    initMap([props.assignProps.orderLocationDto.longitude, props.assignProps.orderLocationDto.latitude])
    getTargetLocationArroundEngineer(props.assignProps)
})

// 派单
function submitAssign(row) {
    if (state.assignedUserId == row.wxUserDto.id || state.assignedUserId) {
        toastWarn('已分配工程师')
        return
    }
    let reqParams = {
        orderId: props.assignProps.orderDto.orderId,
        engineerId: row.wxUserDto.id
    }
    api_orders_dispatch(reqParams)
        .then(res => {
            console.log('dispatch res: ', res)
            toast('指派工程师成功', 'success')
            state.assignedUserId = row.wxUserDto.id
            getTargetLocationArroundEngineer(props.assignProps)
        })
}

// init地图
function initMap(arr) {
    AMapLoader.load({
        key: "c589dad363492c5cd9ba0b62950a9dc8",	// https://console.amap.com/dev/key/app   绑定的服务为 Web端
        version: "2.0",
        plugins: ["AMap.ToolBar", "AMap.ControlBar", 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.Marker', 'AMap.Geolocation'],
    }).then((AMap) => {
        state.map = new AMap.Map('container', {
            viewMode: "2D",  //  是否为3D地图模式
            zoom: 15,
            center: arr,
            resizeEnable: true
        });
        var layer = new AMap.LabelsLayer({
            zooms: [3, 20],
            zIndex: 1000,
            // 开启标注避让，默认为开启，v1.4.15 新增属性
            collision: true,
            // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
            animation: true,
        });
        state.map.add(layer)

        let targetLocation = new AMap.LabelMarker({
            name: '工单地点',
            position: arr,
            opacity: 1,
            zIndex: 10,
            icon: {
                type: 'image',
                image: 'https://vdata.amap.com/icons/b18/1/2.png',
            },
            text: {
                content: '工单地点',
                direction: 'left',
                offset: [0, -5],
            }
        })
        layer.add(targetLocation)

        for (var i = 0; i < engineerList.value.length; i++) {
            var curData = {
                zooms: [10, 20],
                opacity: 1,
                zIndex: 16,
                icon: {
                    type: 'image',
                    image: 'https://a.amap.com/jsapi_demos/static/images/poi-marker.png',
                    clipOrigin: [280, 1],
                    clipSize: [50, 68],
                    size: [25, 34],
                    anchor: 'bottom-center',
                    angel: 0,
                    retina: true
                },
                text: {
                    content: '',
                    direction: 'top',
                    offset: [0, 0],
                    style: {
                        fontSize: 15,
                        fontWeight: 'normal',
                        fillColor: '#333',
                        strokeColor: '#fff',
                        strokeWidth: 2,
                    }
                }
            }
            var engineer = engineerList.value[i]
            curData.name = engineer.wxUserDto.realName
            curData.text.content = engineer.wxUserDto.realName
            curData.position = [engineer.locationDto.longitude, engineer.locationDto.latitude]
            curData.extData = {
                index: i - 1
            };

            var labelMarker = new AMap.LabelMarker(curData);

            layer.add(labelMarker);
        }
        state.map.setFitView();

    }).catch((e) => {
        console.error(e);  //加载错误提示
    }).finally(() => {

    })

}




</script>

<style scoped lang="scss">
.map {
    width: 600px;
    height: 600px;
    padding-top: 20px;
}

#container {
    margin-top: 20px;
    border-radius: 5px;
}

.search-box {
    display: flex;

}

.address {
    margin-left: 20px;
}
</style>